package com.lx.sync.core.util;

import com.lx.sync.core.config.RetryConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * 重试工具类
 */
@Slf4j
public class RetryUtil {

    private static final int DEFAULT_MAX_ATTEMPTS = 3;
    private static final long DEFAULT_INITIAL_INTERVAL = 500L; // 1秒
    private static final double DEFAULT_MULTIPLIER = 2.0;

    /**
     * 同步重试执行
     */
    public static <T> T retry(Callable<T> callable, RetryConfig config) throws Exception {
        int attempts = 0;
        long interval = config.getInitialInterval();

        while (true) {
            try {
                attempts++;
                return callable.call();
            } catch (Exception e) {
                if (attempts >= config.getMaxAttempts()) {
                    log.error("重试{}次后仍然失败", attempts, e);
                    throw e;
                }

                log.warn("第{}次执行失败，将在{}ms后重试", attempts, interval, e);
                Thread.sleep(interval);

                // 计算下次重试间隔
                interval = Math.min(
                        (long) (interval * config.getMultiplier()),
                        config.getMaxInterval()
                );
            }
        }
    }



}
